﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DAL;
using System.Text;

namespace PeisongWeb.admin
{
    public partial class myCustomerOrderList :adminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (hasPermission("IC", 1))
                {
                    drpStatusBind();
                    rptBind();
                }
                else
                {
                    Library.Script.ClientMsgUrl("没有权限！", "index.aspx");
                    return;
                }
            }
        }

        /// <summary>
        /// 列表中的订单状态
        /// </summary>
        private void drpStatusBind()
        {
            drp_Status.DataSource = logic.sysCode.orderStatus();
            drp_Status.DataBind();
            drp_Status.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));

            ddl_orderSource.DataSource = logic.sysCode.orderSource();
            ddl_orderSource.DataBind();
            ddl_orderSource.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));
        }

        /// <summary>
        /// 详细信息中的订单状态
        /// </summary>
        private void drpBind()
        {
            ddl_Status.DataSource = logic.sysCode.orderStatus();
            ddl_Status.DataBind();

            ddl_receiveTime.DataSource = logic.sysCode.receiveTime();
            ddl_receiveTime.DataBind();
        }
        void rptBind()
        {
            int salerepId = logic.sysAdmin.AdminID;
            StringBuilder where = new StringBuilder();
            where.Append("salesperson="+salerepId);
            if (txt_company.Text.Trim() != "")
                where.AppendFormat(" and company like '%{0}%'", txt_company.Text.Trim());
            if (txt_orderNo.Text.Trim() != "")
                where.AppendFormat(" and orderNo = '{0}'", txt_orderNo.Text.Trim());
            if (ext_StartInputDt.SelectedDate != DateTime.MinValue)
                where.AppendFormat(" and datediff(day,[orderDt],'{0}')<=0", ext_StartInputDt.Value.ToString());
            if (ext_EndInputDt.SelectedDate != DateTime.MinValue)
                where.AppendFormat(" and datediff(day,[orderDt],'{0}')>=0", ext_EndInputDt.Value.ToString());
            if (drp_Status.SelectedItem.Value != "")
                where.AppendFormat(" and [status] in ({0})", drp_Status.SelectedItem.Value);
            if (ddl_orderSource.SelectedItem.Value != "")
                where.AppendFormat(" and [source] in ({0})", ddl_orderSource.SelectedItem.Value);
            DataSet ds = logic.order.select(where.ToString(), "orderid desc", AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
            AspNetPager1.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            rpt_list.DataSource = ds.Tables[1];
            rpt_list.DataBind();

            DataTable dt = logic.order.getTotal(where.ToString());
            lbl_orderTotal.Text = string.Format("{0:F2}", dt.Rows[0]["total"]);
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            rptBind();
        }

        //订单列表中的搜索
        protected void btn_select_Click(object sender, EventArgs e)
        {
            rptBind();
        }

        //查看详细信息
        protected void rpt_list_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "details")
            {
                int id = Convert.ToInt32(e.CommandArgument);
                drpBind();
                getDetails(id);
            }
        }
        private void getDetails(int orderid)
        {
            hd_orderid.Value = orderid.ToString();
            DataSet ds = logic.order.select("orderid=" + orderid, "orderid", 1, 1);
            DataRow dr = ds.Tables[1].Rows[0];
            hd_customerid.Value = dr["customerid"].ToString();
            lbl_OrderNo.Text = "订单编号：" + dr["orderNo"].ToString();
            if (dr["source"].ToString() == "1")         //订单来源为网站订单就显示用户名，电话订单就显示录入者
            {
                lbl_user.InnerText = "用户名：";
                lbl_username.Text = dr["username"].ToString();
            }
            else
            {
                lbl_user.InnerText = "录入者：";
                lbl_username.Text = logic.sysAdmin.getById(Convert.ToInt32(dr["customerid"])).Username;
            }
            lbl_orderSource.Text = dr["sourceName"].ToString();     // 订单来源：1、网站订单；2、电话订单
            lbl_orderDt.Text = dr["orderDt"].ToString();            // 下单日期
            ext_receiveDt.SelectedDate = Convert.ToDateTime(dr["receiveDt"]);        //收货日期

            string time = Convert.ToDateTime(dr["receiveDt"]).Hour - 1 + ":00" + "-" + Convert.ToDateTime(dr["receiveDt"]).ToShortTimeString();

            ListItem c = ddl_receiveTime.Items.FindByText(time);

            if (c != null)
            {
                c.Selected = true;
            }
            lbl_Note.Text = dr["note"].ToString();          //订单中的客户备注
            txt_Amount.Value = String.Format("{0:F2}", dr["Amount"]).ToString();    //支付总价
            txt_serviceNote.Text = dr["serviceNote"].ToString();                    //客服备注
            lbl_StandardAmount.Text = String.Format("{0:F2}", dr["standardAmount"]).ToString(); //汇总总价(不算运费和税费)
            ddl_Status.SelectedValue = dr["status"].ToString();         //订单状态
            txt_closeReason.Text = dr["closeReason"].ToString();        //交易关闭原因
            lbl_company.Text = dr["company"].ToString();                //采购商公司名称
            lbl_contact.Text = dr["contact"].ToString();                //联系人
            lbl_contactMobile.Text = dr["contactMobile"].ToString();    //公司联系电话
            lbl_contactPhone.Text = dr["contactPhone"].ToString();          //联系人手机
            lbl_Address.Text = dr["areaName"].ToString() + dr["address"].ToString();    //收货地址
            hd_companyid.Value = dr["companyId"].ToString();                    //采购商ID
            bind(orderid);
            lbl_Total.Text = String.Format("{0:F2}", dr["standardAmount"]);     //订单细目中的汇总价格
            order_details.Show();
        }

        //删除商品
        protected void rpt_OrderItems_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Del")
            {
                int oiid = Convert.ToInt32(e.CommandArgument);
                logic.orderItem.delete(oiid);
                Library.Script.ClientMsg("删除成功！");
                int orderid = Convert.ToInt32(hd_orderid.Value);
                getDetails(orderid);
            }
        }

        /// <summary>
        /// 绑定所选择的订单下的商品信息
        /// </summary>
        /// <param name="orderid"></param>
        void bind(int orderid)
        {
            rpt_OrderItems.DataSource = logic.orderItem.select("orderId=" + orderid, "oiId", 100, 1).Tables[1];
            rpt_OrderItems.DataBind();
        }

        protected void lbtn_Search_Click(object sender, EventArgs e)
        {
            rptBind();
        }


        [Coolite.Ext.Web.AjaxMethod]
        public string orderList_getDetails(int productid)
        {
            DataTable dt = logic.files.getListByProduct(productid);
            return Library.Resource.UploadPath + Library.Resource.FileThumbnail1 + "/" + dt.Rows[0]["systemName"].ToString();

        }
    }
}
